package vn.ikame.android.utils;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

public class CommonUtils {

	public static final boolean LOG_DEBUG = true;
//	public static final String TGCT_SDCARD_PATH = Environment
//			.getExternalStorageDirectory().getAbsolutePath()
//			+ "/fma/video/";
	
	/** LOG TAG. */
	private static final String TAG = "CommonUtils";

	private static final SimpleDateFormat sSQLiteFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private static final DateFormat sDateFormat = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss");
	/** Date format "yyyy:MM:dd HH:mm:ss". */
	private static final DateFormat sAltDateFormat = new SimpleDateFormat(
			"yyyy:MM:dd HH:mm:ss");
	public static String TIME_SIMPLE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/**
	 * Write the content boundary + extra to the specified output stream.
	 * 
	 * @param out
	 *            The output stream
	 * @param twoHyphens
	 *            Extra characters
	 * @param multipartBoundary
	 *            The boundary as a byte array.
	 * @param end
	 *            The newline character
	 * @throws UnexpectedException
	 *             If an IO problem occurs.
	 */
	public static void writeBoundaryExtra(OutputStream out, byte[] twoHyphens,
			byte[] multipartBoundary, byte[] end) throws IOException {
		out.write(twoHyphens);
		out.write(multipartBoundary);
		out.write(end);
	}

	/**
	 * Encode a code body to String which use when upload.
	 * 
	 * @param parameters
	 *            mapping from String values to various Parcelable types.
	 * @param boundary
	 * 
	 * @return String The string is encode.
	 */
	public static String encodePostBody(final Bundle parameters,
			final String boundary) {
		if (parameters == null) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (String key : parameters.keySet()) {
			sb.append("Content-Disposition: form-data; name=\"" + key
					+ "\"\r\n\r\n" + parameters.getString(key));
			sb.append("\r\n" + "--" + boundary + "\r\n");
		}

		return sb.toString();
	}

	/**
	 * Check network connection. End processing if there is no connection.
	 * 
	 */
	public static boolean isNetworkConnected(Context ctx) {
		ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo == null) {
			return false;
		}
		return true;
	}
	
	/**
	 * Log info.
	 * 
	 * @param tag
	 *            tag name
	 * @param msg
	 *            message wants to log
	 */
	public static void logError(final String tag, final String msg) {
		if (LOG_DEBUG && !TextUtils.isEmpty(msg)) {
			Log.e(tag, msg);
		}
	}

	/**
	 * Log debug.
	 * 
	 * @param tag
	 *            tag name
	 * @param msg
	 *            message wants to log
	 */
	public static void logDebug(final String tag, final String msg) {
		if (LOG_DEBUG && !TextUtils.isEmpty(msg)) {
			Log.d(tag, msg);
		}
	}

	/**
	 * Log info.
	 * 
	 * @param tag
	 *            tag name
	 * @param msg
	 *            message wants to log
	 */
	public static void logInfo(final String tag, final String msg) {
		if (LOG_DEBUG && !TextUtils.isEmpty(msg)) {
			Log.i(tag, msg);
		}
	}

	/**
	 * Convert [YYYY-MM-DD] to [YYYY/MM/DD].
	 * 
	 * @param strMinDay
	 *            date with format [YYYY-MM-DD]
	 * @return date with format [YYYY/MM/DD]
	 */
	public static String convertToKatamaryDate(final String strMinDay) {
		String katamaryDate = "";
		if (TextUtils.isEmpty(strMinDay)) {
			return "";
		}
		String[] temps = strMinDay.split("-");
		if (temps != null && temps.length == 3) {
			katamaryDate = temps[0] + "/" + temps[1] + "/" + temps[2];
		} else {
			return "";
		}
		return katamaryDate;
	}

	/**
	 * Parse string date "yyyy-MM-dd'T'HH:mm:ss" or "yyyy:MM:dd HH:mm:ss" to
	 * long milisecond time.
	 * 
	 * @param strDate
	 *            format "yyyy-MM-dd'T'HH:mm:ss" or "yyyy:MM:dd HH:mm:ss"
	 * @return String milisecond time.
	 */
	public static String parseDateToLong(final String strDate) {
		try {
			final Date date = sDateFormat.parse(strDate);
			return String.valueOf(date.getTime());
		} catch (ParseException e) {
			try {
				final Date date = sAltDateFormat.parse(strDate);
				return String.valueOf(date.getTime());
			} catch (ParseException ex) {
				CommonUtils
						.logInfo(TAG, "Unalble to parse date string to long");
			}
		} catch (NullPointerException e) {
			CommonUtils.logInfo(TAG, "Unalble to parse empty date string");
		}
		return "0";
	}

	/**
	 * Parse string date "yyyy-MM-dd'T'HH:mm:ss" or "yyyy:MM:dd HH:mm:ss" to sql
	 * date string "yyyy-MM-dd HH:mm:ss".
	 * 
	 * @param strDate
	 *            format "yyyy-MM-dd'T'HH:mm:ss" or "yyyy:MM:dd HH:mm:ss"
	 * @return sql date string "yyyy-MM-dd HH:mm:ss"
	 */
	public static String parserDateToSqlDate(final String strDate) {
		try {
			final Date date = sDateFormat.parse(strDate);
			return sSQLiteFormat.format(date);
		} catch (ParseException e) {
			try {
				final Date date = sAltDateFormat.parse(strDate);
				return sSQLiteFormat.format(date);
			} catch (ParseException e1) {
				Log.i(TAG, "Unalble to parse date string to sqlite date string");
			}
		}
		return "";
	}

	/**
	 * Parse long value to sql date string by "yyyy-MM-dd HH:mm:ss" format.
	 * 
	 * @param calendar
	 *            calendar to parse data
	 * @param time
	 *            time in milisecond
	 * @return sql date string "yyyy-MM-dd HH:mm:ss"
	 */
	public static String parserLongToSqlDate(Calendar calendar, long time) {
		calendar.setTimeInMillis(time);
		return sSQLiteFormat.format(calendar.getTime());
	}

	/**
	 * Check whether a url is valid or not.
	 * 
	 * @param url
	 *            the url wants to check
	 * @return true if url is valid
	 */
	public static boolean isValidURL(String url) {
		if (!TextUtils.isEmpty(url)
				&& (url.startsWith("http") || url.startsWith("https"))) {
			return true;
		}
		return false;
	}

	/**
	 * Create folder in SDCard.
	 * 
	 * @param path
	 *            dir of folder want to create
	 */
	public static void createFolder(final String path) {
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		System.out.println("Folder  " + path);
	}

	/**
	 * Check whether a file exists or not.
	 * 
	 * @param localPath
	 *            specified file path
	 * @return true if file exists
	 */
	public static boolean isFileExist(String localPath) {
		if (TextUtils.isEmpty(localPath)) {
			return false;
		}
		File file = new File(localPath);
		{
			return file.exists();
		}
	}

	public static boolean appInstalledOrNot(Context context, String uri) {
		PackageManager pm = context.getPackageManager();
		boolean app_installed = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			app_installed = false;
		}
		return app_installed;
	}
}
